package com.lebang.cecartoon;


import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @version V1.0
 * @author: zpc
 * @date:
 */

@SpringBootApplication
public class VoicecartoonAdminApplication {
    public static void main(String[] args) throws Exception {
        Map<String, Object> valueMap = new HashMap<>();
        //接口名称
        valueMap.put("ifName", "openapi");
        //包名
        valueMap.put("package", "com.lebang.cecartoon.service");
        //swgger介绍名称
        valueMap.put("swgget_api_name", "测试");
        //controller名称
        valueMap.put("controller_class_name", "BackgroundStyleController");
        //service名称
        valueMap.put("service_class_name", "StyleService");
        //mapper名称
        valueMap.put("mapper_class_name", "BackgroundStyleMapper");
        //po名称
        valueMap.put("po_class_name", "BackgroundStyle");

        gen(valueMap, ".", "src\\main\\java\\com\\lebang\\cecartoon\\class.ftl",
                "src/main/gen",  "BackgroundStyleController.java");
        gen(valueMap, ".", "src\\main\\java\\com\\lebang\\cecartoon\\service.ftl",
                "src/main/gen",  "StyleService.java");

    }
    public static void gen(Map<String, Object> valueMap, String useTemplatePath, String useTemplateName,
                            String outPutPath,String genFileName) throws Exception {

        final String ENCODING = "UTF-8";
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        contextClassLoader.getResource(useTemplatePath);
        // 指定模板存放的路径
        TemplateLoader loader = new FileTemplateLoader(new File(useTemplatePath));

        Configuration cfg = new Configuration();
        cfg.setTemplateLoader(loader);
        cfg.setEncoding(Locale.getDefault(), ENCODING);

        // 指定使用的模板
        Template template = cfg.getTemplate(useTemplateName, ENCODING);
        template.setEncoding(ENCODING);

        // 生成代码的路径 replace替换的只能是字符，replaceAll则是正则
        File filePath = new File(outPutPath); // replaceAll ???
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        // 生成的代码位置和名字
        File targetFile = new File(filePath, genFileName);
        if (targetFile.exists()) {
            targetFile.delete();
        }

        template.process(valueMap, new OutputStreamWriter(new FileOutputStream(targetFile, false), ENCODING));
    }


}
